package com.bootdo.app.common.utils;

import java.math.BigDecimal;

/**
  * @auther: Along
  * @description: 请求状态工具类 （防止盗链）
  */
public class StateUtil {

    private static final char[] CHARS = {'Q','P','s','a','K','N','X','T','E','z'};
    private static final char[] INDEX  = {'0','1','2','3','4','5','6','7','8','9'};

    /**
     * 生成状态码
     * @return
     */
    public static String getStateStr(){
        char[] chars = String.valueOf(System.currentTimeMillis() / 1000).toCharArray();
        StringBuffer sb = new StringBuffer();
        for(char c : chars){
            for(int i = 0; i < INDEX.length; i++){
                if(c == INDEX[i]){
                    sb.append(CHARS[i]);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 校验状态码
     * @param stateStr StateUtil工具类生产的状态码
     * @param seconds 秒数
     * @return
     */
    public static boolean checkState(String stateStr,long seconds){
        char[] chars = stateStr.toCharArray();
        StringBuffer sb = new StringBuffer();
        for(char c : chars){
            for(int i = 0; i < CHARS.length; i++){
                if(c == CHARS[i]){
                    sb.append(INDEX[i]);
                }
            }
        }
        long startTime = Long.parseLong(sb.toString());
        long now = System.currentTimeMillis() / 1000;
        BigDecimal decimal_now = new BigDecimal(now);
        BigDecimal decimal_start = new BigDecimal(startTime);
        if(decimal_now.subtract(decimal_start).abs().longValue() < seconds){
            return true;
        }
        return false;
    }
    public static void main(String[] args) {
        final String stateStr = getStateStr();
        System.out.println(stateStr);
        System.out.println(checkState(stateStr,100));

    }

}
